package com.mingte.manghe.filter;

import com.alibaba.fastjson.JSONObject;
import com.mingte.manghe.common.ResponseResult;
import com.mingte.manghe.config.ThreadPoolConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author ：luxinsheng
 * @Email ：282860642@qq.com
 * @date ：Created in 2021/11/25 11:24
 * @description：请求过滤
 * @modified By：
 * @version: $
 */
@Component
@WebFilter(filterName = "UrlFilter", urlPatterns = "/**")
public class UrlFilter implements Filter {

    private final Logger logger = LoggerFactory.getLogger(UrlFilter.class);

    @Resource
    private ThreadPoolConfig threadPoolConfig;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("启动"+filterConfig.getFilterName()+"过滤器");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        try {


            //请求预检设置响应
            resp.addHeader("Access-Control-Allow-Origin","*");//允许跨域请求
            resp.addHeader("Access-Control-Allow-Methods","GET,POST");//真实请求允许的方法
            resp.addHeader("Access-Control-Allow-Headers","token,Origin,X-Requested-With,Content-Type,Accept");//服务器允许使用的字段
            resp.addHeader("Access-Control-Allow-Credentials","true");//是否允许用户发送、处理 cookie
            resp.addHeader("Access-Control-Max-Age","3600");//预检请求的有效期，单位为秒。有效期内，不会重复发送预检请求
            resp.setCharacterEncoding("UTF-8");

            logger.info("请求URL{}",req.getRequestURI());

            filterChain.doFilter(req, resp);
        } catch (IOException e) {
            logger.error("filter过滤IO异常{}",e.getMessage());
        } catch (ServletException e) {
            logger.error("filter过滤servlet异常{}",e.getMessage());
        }
    }

    @Override
    public void destroy() {
        System.out.println("销毁了");
        List<Runnable> shutdown = threadPoolConfig.shutdown();
        for (Runnable runnable:shutdown) {
            System.out.println(runnable.hashCode());
        }
    }
}
